package top.heue.utils.lifecycle.helper

import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner

class ViewModelFactory(private vararg val params: Any) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val types = mutableListOf<Class<*>>()
        val values = mutableListOf<Any>()
        params.forEach {
            types.add(it::class.java)
            values.add(it)
        }
        return modelClass.getConstructor(*types.toTypedArray()).newInstance(*values.toTypedArray())
    }
}

/** 通用的ViewModel实例化*/
inline fun <reified T : ViewModel> viewModelS(
    owner: ViewModelStoreOwner, vararg params: Any
) = lazy {
    ViewModelProvider(owner, ViewModelFactory(*params))[T::class.java]
}

/** Fragment的ViewModel实例化*/
inline fun <reified T : ViewModel> Fragment.viewModel(
    vararg params: Any
) = viewModelS<T>(this, *params)

/** ComponentActivity的ViewModel实例化*/
inline fun <reified T : ViewModel> ComponentActivity.viewModel(
    vararg params: Any
) = viewModelS<T>(this, *params)
